package com.bijiawang.user.config;

import com.bijiawang.user.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.sql.DataSource;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Qualifier("userDetailsServiceImpl")
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/index.html").permitAll()
                .antMatchers("/css/**","/fonts/**","/images/**","/js/**","/style.css").permitAll()
                .antMatchers("/search").permitAll()
//                .antMatchers("/sethistory").permitAll()
                .antMatchers("/handle_form").permitAll()
                .antMatchers("/checkEmail/**").permitAll()
                .antMatchers("/checkUsername/**").permitAll()
                .antMatchers("/checkPhonename/**").permitAll()
                .antMatchers("/change/checkCode/**").permitAll()
                .antMatchers("/change/forgetpasw").permitAll()
                .antMatchers("/change/tochangepasw").permitAll()
                .antMatchers("/sendEmail/**").permitAll()
                .antMatchers("index").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/verify/**").permitAll()
                .antMatchers("/captcha/**").permitAll()
                .anyRequest().authenticated();

        http.formLogin().loginPage("/userLogin").permitAll()
                .usernameParameter("phoneNumber")
                .passwordParameter("pwd")
                .defaultSuccessUrl("/")
                .failureUrl("/userLogin?error");

        http.logout().logoutUrl("/mylogout").logoutSuccessUrl("/");

        http.rememberMe()
                .rememberMeParameter("rememberme")
                .tokenValiditySeconds(200);//保存200秒
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //Security版本高，要有密码编码器
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(encoder);

    }
}
